﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using AmiCheckin.Lib;
using AmiCheckin.Lib.Model;

namespace AmiCheckin.Code.Util
{
    public class ConfigUtil
    {
        static JsonSerializerOptions opt = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };

        public static AmiCheckinConfig GetConfig()
        {
            try
            {
                var path = PathUtil.ConfigPath;

                if (File.ReadAllText(path) == string.Empty)
                {
                    File.WriteAllText(path, JsonSerializer.Serialize(
                        GetDefault(), opt
                    ));
                }

                return JsonSerializer.Deserialize<AmiCheckinConfig>(File.ReadAllText(path), opt);
            }
            catch (Exception)
            {
                return new();
            }
        }

        public static void SetConfig(AmiCheckinConfig cfg)
        {
            var path = PathUtil.ConfigPath;
            File.WriteAllText(path, JsonSerializer.Serialize(cfg, opt));
        }


        //获取默认的Config
        public static AmiCheckinConfig GetDefault()
        {
            return new AmiCheckinConfig()
            {
                SaveMode = LocationType.INI,
                CheckinSets = new Dictionary<string, CheckinSet>()
                {
                    {
                        "AmiCoinSet", new()
                        {
                            Keywords = new(),
                            Replies = new[] { "[at]", "签到成功~", "获得了[coin]" }.ToList(),
                            Rewards = new()
                            {
                                { "Ami积分", new(10, 20) }
                            },
                        }
                    }
                },
                RewardTypes = new()
                {
                    { "Ami积分", new()
                    {
                        Path = "Config\\Ami\\[qq].ini",
                        Args = new []{"Coins","Ami积分"}.ToList(),
                        LocationType = LocationType.INI,
                        
                    } }
                }
            };
        }
    }
}